package com.muye.dianli;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.mime.content.StringBody;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.directionalviewpager.DirectionalViewPager;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.muye.adapter.FragmentAdapter;
import com.muye.constant.C;
import com.muye.constant.ConstantPersonalInfo;
import com.muye.constant.U;
import com.muye.dianli.activity.AboutUsActivity;
import com.muye.dianli.activity.CouponListActivity;
import com.muye.dianli.activity.FollowListActivity;
import com.muye.dianli.activity.MapActivity;
import com.muye.dianli.activity.MemberCardActivity;
import com.muye.dianli.activity.MineActivity;
import com.muye.dianli.activity.OrderListActivity;
import com.muye.dianli.activity.SettingActivity;
import com.muye.dianli.fragment.MainFragment0;
import com.muye.dianli.fragment.MainFragment1;
import com.muye.dianli.fragment.MainFragment2;
import com.muye.dianli.fragment.MainFragment3;
import com.muye.field.HomePageList;
import com.muye.field.HomePageListData;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 首页
 * 
 * @author TangChao
 * 
 */
public class MainActivity extends FragmentActivity implements OnClickListener, OnKeyListener
{
	/**
	 * 侧滑按钮
	 */
	private SlidingMenu menu;
	
	/**
	 * 侧滑菜单View对象
	 */
	private View slidingView;
	
	/**
	 * 请求数据线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	/**
	 * 页面适配器
	 */
	private FragmentAdapter adapter;
	
	/**
	 * ViewPager
	 */
	private DirectionalViewPager viewPager;
	
	/**
	 * 数据源
	 */
	private List<List<HomePageListData>> dataList;
	
	/**
	 * 装载有碎片页面的数据
	 */
	private ArrayList<SparseArray<Fragment>> arrayList;
	
	/**
	 * 页面碎片映射
	 */
	private SparseArray<Fragment> sparseArray;
	
	/**
	 * 热点文章页面
	 */
	private MainFragment0 fragment0;
	
	/**
	 * 促销活动页面
	 */
	private MainFragment1 fragment1;
	
	/**
	 * 活动优惠页面
	 */
	private MainFragment2 fragment2;
	
	/**
	 * 产品页面
	 */
	private MainFragment3 fragment3;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.main_layout);
		createTitle();
		initWidget();
		// 加载侧滑菜单
		menu = new SlidingMenu(this);
		menu.setMode(SlidingMenu.LEFT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		menu.setBehindOffset((getWindowManager().getDefaultDisplay().getWidth() / 4));
		menu.setBehindWidth((getWindowManager().getDefaultDisplay().getWidth() / 4) * 3);
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		slidingView = LayoutInflater.from(this).inflate(R.layout.sliding_menu_layout, null);
		menu.setMenu(slidingView);
		// 请求数据
		// getHomePageList();
		dataList = C.MAIN_DATA;
		
		/* ============================ */
		fragment0 = new MainFragment0();
		fragment0.setArrayList(dataList.get(0));
		/* ============ */
		fragment1 = new MainFragment1();
		fragment1.setArrayList(dataList.get(1));
		/* ============ */
		fragment2 = new MainFragment2();
		fragment2.setArrayList(dataList.get(2));
		/* ============ */
		fragment3 = new MainFragment3();
		try
		{
			fragment3.setArrayList(dataList.get(3));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		/* ============ */
		arrayList = new ArrayList<SparseArray<Fragment>>();
		sparseArray = new SparseArray<Fragment>(4);
		sparseArray.put(0, fragment0);
		sparseArray.put(1, fragment1);
		sparseArray.put(2, fragment2);
		sparseArray.put(3, fragment3);
		arrayList.add(sparseArray);
		adapter = new FragmentAdapter(getSupportFragmentManager(), arrayList);
		viewPager.setAdapter(adapter);
		/* ============================ */
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		initSlidingWidget(slidingView);
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		menu.removeView(slidingView);
		// handler.removeCallbacks(requestHttpPostThread);
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("点利商盟");
		ImageView titleLeftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		titleLeftBtn.setVisibility(View.VISIBLE);
		titleLeftBtn.setImageResource(R.drawable.main_title_left_icon);
		titleLeftBtn.setOnClickListener(this);
		ImageView titleRightBtn = (ImageView) findViewById(R.id.title_bar_right_image_view);
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn.setImageResource(R.drawable.main_title_right_icon);
		titleRightBtn.setOnClickListener(this);
	}
	
	/**
	 * 初始化控件
	 */
	private void initWidget()
	{
		viewPager = (DirectionalViewPager) findViewById(R.id.main_layout_view_pager);
		viewPager.setOrientation(DirectionalViewPager.VERTICAL);
	}
	
	/**
	 * 初始化侧滑菜单布局控件
	 */
	private void initSlidingWidget(View view)
	{
		// 登录布局
		RelativeLayout loginRelativeLayout = (RelativeLayout) view.findViewById(R.id.sliding_menu_layout_login_relative);
		loginRelativeLayout.setOnClickListener(this);
		// 用户头像
		ImageView userImage = (ImageView) view.findViewById(R.id.sliding_menu_layout_user_image);
		// 登录状态按钮
		TextView loginStatus = (TextView) view.findViewById(R.id.sliding_menu_layout_login_text);
		// 用户名
		TextView userName = (TextView) view.findViewById(R.id.sliding_menu_layout_nick_name);
		if (ConstantPersonalInfo.uid != null && !ConstantPersonalInfo.uid.equals(""))// 登录
		{
			if (ConstantPersonalInfo.sex.equals("2"))// 女
			{
				userImage.setImageResource(R.drawable.user_image_female);
			}
			else if (ConstantPersonalInfo.sex.equals("1"))// 男
			{
				userImage.setImageResource(R.drawable.user_image_male);
			}
			loginStatus.setText("注销");
			userName.setText("昵称: " + ConstantPersonalInfo.name);
			userName.setVisibility(View.VISIBLE);
		}
		else
		// 未登录
		{
			userImage.setImageResource(R.drawable.user_image_unlogin);
			loginStatus.setText("登录");
			userName.setText("");
			userName.setVisibility(View.GONE);
		}
		// 我的
		TextView mineBtn = (TextView) view.findViewById(R.id.sliding_menu_layout_mine);
		mineBtn.setOnClickListener(this);
		// 我的收藏
		TextView myFavouriteBtn = (TextView) findViewById(R.id.sliding_menu_layout_my_favourite);
		myFavouriteBtn.setOnClickListener(this);
		// 我的订单
		TextView myOrder = (TextView) findViewById(R.id.sliding_menu_layout_my_order);
		myOrder.setOnClickListener(this);
		// 会员卡
		TextView memberCard = (TextView) findViewById(R.id.sliding_menu_layout_member_card);
		memberCard.setOnClickListener(this);
		// 优惠券
		TextView coupon = (TextView) findViewById(R.id.sliding_menu_layout_coupon);
		coupon.setOnClickListener(this);
		// 设置
		TextView setting = (TextView) findViewById(R.id.sliding_menu_layout_setting);
		setting.setOnClickListener(this);
		// 关于我们
		TextView about = (TextView) findViewById(R.id.sliding_menu_layout_about);
		about.setOnClickListener(this);
	}
	
	/**
	 * 请求首页列表
	 */
	private void getHomePageList()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(getHomePagerListener, U.HOME_PAGE_LIST, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求首页列表返回监听
	 */
	private RequestHttpListener getHomePagerListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "首页请求结果----->" + str);
					Gson gson = new Gson();
					HomePageList homePageList = gson.fromJson(str, HomePageList.class);
					dataList = homePageList.data;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							// fragment0 = new MainFragment0();
							// fragment0.setArrayList(dataList.get(0));
							// /* ============ */
							// fragment1 = new MainFragment1();
							// fragment1.setArrayList(dataList.get(1));
							// /* ============ */
							// fragment2 = new MainFragment2();
							// fragment2.setArrayList(dataList.get(2));
							// /* ============ */
							// fragment3 = new MainFragment3();
							// try
							// {
							// fragment3.setArrayList(dataList.get(3));
							// }
							// catch (Exception e)
							// {
							// e.printStackTrace();
							// }
							// /* ============ */
							// arrayList = new ArrayList<SparseArray<Fragment>>();
							// sparseArray = new SparseArray<Fragment>(4);
							// sparseArray.put(0, fragment0);
							// sparseArray.put(1, fragment1);
							// sparseArray.put(2, fragment2);
							// sparseArray.put(3, fragment3);
							// arrayList.add(sparseArray);
							// adapter = new FragmentAdapter(getSupportFragmentManager(), arrayList);
							// viewPager.setAdapter(adapter);
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(getApplicationContext(), "请求失败,请重试");
							break;
						
						default:
							break;
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	/**
	 * 点击空白处隐藏键盘
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		try
		{
			InputMethodManager imeMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imeMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return super.onTouchEvent(event);
	}
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:// 左按钮
				menu.showMenu();
				break;
			case R.id.title_bar_right_image_view:// 地图按钮
				Intent intent0 = new Intent(MainActivity.this, MapActivity.class);
				slidingView.getContext().startActivity(intent0);
				break;
			case R.id.sliding_menu_layout_login_relative:// 登录按钮
				if (C.isLogin(MainActivity.this))
				{
					ConstantPersonalInfo.uid = "";
					C.showToast(MainActivity.this, "注销成功");
					finish();
				}
				break;
			case R.id.sliding_menu_layout_mine:// 我的按钮
				if (C.isLogin(MainActivity.this))
				{
					Intent intent1 = new Intent(MainActivity.this, MineActivity.class);
					slidingView.getContext().startActivity(intent1);
				}
				break;
			case R.id.sliding_menu_layout_my_favourite:// 我的收藏按钮
				if (C.isLogin(MainActivity.this))
				{
					Intent intent2 = new Intent(MainActivity.this, FollowListActivity.class);
					slidingView.getContext().startActivity(intent2);
				}
				break;
			case R.id.sliding_menu_layout_my_order:// 我的订单按钮
				if (C.isLogin(MainActivity.this))
				{
					Intent intent3 = new Intent(MainActivity.this, OrderListActivity.class);
					slidingView.getContext().startActivity(intent3);
				}
				break;
			case R.id.sliding_menu_layout_member_card:// 会员卡按钮
				if (C.isLogin(MainActivity.this))
				{
					Intent intent4 = new Intent(MainActivity.this, MemberCardActivity.class);
					slidingView.getContext().startActivity(intent4);
				}
				break;
			case R.id.sliding_menu_layout_coupon:// 优惠券按钮
				if (C.isLogin(MainActivity.this))
				{
					Intent intent5 = new Intent(MainActivity.this, CouponListActivity.class);
					slidingView.getContext().startActivity(intent5);
				}
				break;
			case R.id.sliding_menu_layout_setting:// 设置按钮
				Intent intent6 = new Intent(MainActivity.this, SettingActivity.class);
				slidingView.getContext().startActivity(intent6);
				break;
			case R.id.sliding_menu_layout_about:// 关于按钮
				Intent intent7 = new Intent(MainActivity.this, AboutUsActivity.class);
				slidingView.getContext().startActivity(intent7);
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
	
}
